<template>
  <div>
    <div class="upload_container">
      <h3>单一文件上传「BASE64」, 只适合图片</h3>

      <div class="upload_box">
        <input
          ref="baseimg"
          @change="getFile"
          type="file"
          class="upload_ipu"
        />
        <div class="upload_button_group">
          <button
            class="upload_button"
            @click="selectFile"
          >
            上传图片
          </button>
        </div>
        <div class="upload_tips">
          只能上传 PNG/JPG/JPEG 格式图片，且大小不能超过2MB
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  mounted() {},
  methods: {
    selectFile() {
      this.$refs["baseimg"].click();
    },
    async getFile(event) {
        this.files = event.target.files["0"];

        if(this.files.size > 2 * 1024 * 1024){
            this.$message.warning("上传的文件不能大于2MB");
            return;
        }


        const type = this.files.type;
        if(!/( PNG|JPG|JPEG|GIF)/i.test(type)){
            this.$message.warning("上传的文件类型不正确");
            return;
        }


        this.progressStatus = true;
        let fromData = new FormData();
        fromData.append("file", this.files);
        fromData.append("filename", this.files.name);
        const res = await uploadSingle(fromData, (loaded, total) => {
            this.uploadProgress = (loaded / total) * 100;
        })
        // console.log(res);
        if(res.data.code == 0){
            this.$message.success("文件上传成功")
            this.$message.success({
                message: '文件地址: ' + res.data.servicePath,
                offset: 60,
            })
            this.files = "";
            this.uploadProgress = 0;
            this.progressStatus = false;
        }
    },
  },
};
</script>

<style scoped lang='scss'>
.upload_container {
  padding: 40px;
}
.upload_container h3 {
  font-size: 18px;
  font-weight: 700;
}
.upload_box {
  border: 1px dashed #ddd;
  padding: 20px;
  width: 340px;
  min-height: 120px;
}
.upload_button {
  border: none;
  background: antiquewhite;
  color: #fff;
  font-size: 12px;
  text-align: center;
  padding: 0 10px;
  height: 24px;
  line-height: 24px;
  margin-right: 10px;
  cursor: pointer;
  border-radius: 5px;
  background-color: rgb(3, 151, 250);
  position: relative;
}
.upload_ipu {
  display: none;
}
.upload_tips {
  color: #3d3d3d;
  font-size: 12px;
  margin-top: 10px;
}
</style>
